<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html xmlns='http://www.w3.org/1999/xhtml'
	xmlns:v='urn:schemas-microsoft-com:vml'>

<head>
<meta http-equiv='content-type' content='text/html; charset=UTF-8' />
<meta http-equiv='cache-control' content='no-cache' />
<meta http-equiv='expires' content='0' />
<meta name='copyright' content='Copyright (C) XXX Consultants' />
<meta name='robots' content='none' />

<link rel="stylesheet" href="/gts/css/main.css" />
<link rel="shortcut icon" href="/gts/images/favicon.ico"
	type="image/x-icon" />

<title>XXX Tracking System</title>


<!-- Begin Page JavaScript -->
<script src="/gts/js/utils.js" type="text/javascript"></script>
<script
	src='http://dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.1'
	type="text/javascript"></script>

<script type="text/javascript">
<!--
var HEADING = new Array('N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW' );
var MAX_PUSH_PINS           = 500;
var virtEarthColorIcon      = null;
var virtEarthDetailPoints   = null;
var virtEarthLastEventTime  = '2007/03/13 19:52:46 GMT';
var virtEarthDetailsEnabled = false;
var virtEarthMap            = null;
var virtEarthDrawLayer      = null;
var virtEarthZoneRadiusM    = 700.0;


//XXX data table
function vearthShowDetails() {
  var table = document.getElementById('trackMapDataTable');
  if (table == null) { return; }
  var html = '';  
  var pt = virtEarthDetailPoints;
  if (virtEarthDetailsEnabled && (pt != null) && (pt.length > 0)) {
    html += '<table cellspacing=0 cellpadding=0 border=1>\n';
    html += '<thead><tr>';
    html += '<th width=25  nowrap style="border-bottom-style:solid;border-width:1px;"><center><b><font face=arial size=-1>#</font></b></center></th>';
    html += '<th width=125 nowrap style="border-bottom-style:solid;border-width:1px;"><center><b><font face=arial size=-1>Date/Time</font></b></center></th>';
    html += '<th width=75  nowrap style="border-bottom-style:solid;border-width:1px;"><center><b><font face=arial size=-1>Code</font></b></center></th>';
    html += '<th width=110 nowrap style="border-bottom-style:solid;border-width:1px;"><center><b><font face=arial size=-1>Lat/Lon</font></b></center></th>';
    html += '<th width=60  nowrap style="border-bottom-style:solid;border-width:1px;"><center><b><font face=arial size=-1>MPH</font></b></center></th>';
    html += '<th width=250 nowrap style="border-bottom-style:solid;border-width:1px;"><center><b><font face=arial size=-1>Address</font></b></center></th>';
    html += '</tr></thead>\n';
    html += '<tbody>\n';
    for (var i = 0; i < pt.length; i++) {
      html += '<tr>';
      html += '<td nowrap><center>' + pt[i].index    + '</center></td>';
      html += '<td nowrap><center>' + pt[i].dateTime + '</center></td>';
      html += '<td nowrap><center>' + pt[i].code     + '</center></td>';
      html += '<td nowrap><center>' + pt[i].latlon   + '</center></td>';
      html += '<td nowrap><center>' + pt[i].velocity + '</center></td>';
      html += '<td nowrap>' + pt[i].address  + '&nbsp;</td>';
      html += '</tr>\n';
    }
    html += '</tbody>\n';
    html += '</table>\n';
  }
  table.innerHTML = html;
}


function vearthDetailPoint(dev, lat, lon, ndx, code, dtime, spd, hdg, alt, addr) {
  var spdfmt    = numFormatFloat(spd,1);
  if (spd >= 0.1) { spdfmt += ' ' + hdg; };
  this.device   = dev;
  this.latlon   = numFormatFloat(lat,4) + '/' + numFormatFloat(lon,4);
  this.index    = ndx;
  this.code     = code;
  this.dateTime = dtime;
  this.velocity = spdfmt;
  this.altitude = alt;
  this.address  = addr;
}
function vearthInit() {
  if (virtEarthColorIcon == null) {
    virtEarthColorIcon = new Array(
      'http://labs.google.com/ridefinder/images/mm_20_black.png',
      'http://labs.google.com/ridefinder/images/mm_20_brown.png',
      'http://labs.google.com/ridefinder/images/mm_20_red.png',
      'http://labs.google.com/ridefinder/images/mm_20_orange.png',
      'http://labs.google.com/ridefinder/images/mm_20_yellow.png',
      'http://labs.google.com/ridefinder/images/mm_20_green.png',
      'http://labs.google.com/ridefinder/images/mm_20_blue.png',
      'http://labs.google.com/ridefinder/images/mm_20_purple.png',
      'http://labs.google.com/ridefinder/images/mm_20_gray.png',
      'http://labs.google.com/ridefinder/images/mm_20_white.png'
    );
  }
       
  if (virtEarthMap == null) {
    virtEarthMap = new VEMap('verth');
    virtEarthMap.LoadMap();
    virtEarthDrawLayer = new VEShapeLayer();
    virtEarthMap.AddShapeLayer(virtEarthDrawLayer);
    document.getElementById('verth').style.cursor='crosshair';
  }
  virtEarthMap.AttachEvent('onmousemove', EventHandler_OnMouseMove);
}


function vearthCreatePushPin(dev,lat,lon,ndx,code,icon,date,time,spd,hdg) {
    var flat   = lat;
    var flon   = lon;
    var spdfmt = spd + " mph";
    if (spd >= 0.1) { spdfmt += ' ' + hdg; };
    
    var html = '';
    html += '<table>';    
    html += '<tr><td align=left nowrap><small>Date: ' + date + ' ' + time + '</small></td></tr>';
    html += '<tr><td align=left nowrap><small>GPS: ' + flat + ' / ' + flon + '</small></td></tr>';
    html += '<tr><td align=left nowrap><small>Speed: ' + spdfmt  + '</small></td></tr>';
    html += '</table>';
    var pin = new VEShape(VEShapeType.Pushpin, new VELatLong(lat,lon));
    pin.SetTitle('<small>[#' + ndx + '] <b>' + dev + ' : ' + code + '</b></small>');
    

    
    pin.SetDescription(html);
    var pushPinURL = vearthGetIcon(icon);
    var imgURL = "<div style='position: relative; top: -6px; left: 6px'><img src='"+pushPinURL+"'></div>";
    pin.SetCustomIcon(imgURL);
    return pin;
}

function vearthGetIcon(icon) {
  if ((icon >= 0) && (icon < 10)) {
    return virtEarthColorIcon[icon];
  } else {
    return virtEarthColorIcon[0];
  }
}
function vearthSetMap(recenter,centerLat,centerLon,zoomFactor,points,pushPins,inclLine) {
  virtEarthMap.DeleteAllShapes();
  virtEarthMap.DeleteAllPolylines();
  
  // line
  if (inclLine) { virtEarthMap.AddPolyline(new VEPolyline('routeLine',points,new VEColor(255,34,34,1), 2)); }
  
  //points
  if (pushPins != null) {
    for (var i = 0; i < pushPins.length; i++) {
      virtEarthMap.AddShape(pushPins[i]);
    }
  }
  
  //set center
  if (recenter && ((centerLat != 0) || (centerLon != 0))) {
    var ct = new VELatLong(centerLat, centerLon);
    if (zoomFactor > 0) {
      virtEarthMap.SetCenterAndZoom(ct, zoomFactor);
    } else {
      virtEarthMap.SetCenter(ct);
    }
  } else {
    virtEarthMap.SetMapView(points);
  }
}
function vearthGetXMLHttpRequest() {
  var req = null;
  if (window.XMLHttpRequest) {
    try {
      req = new XMLHttpRequest();
    } catch(e) {
      req = null;
    }
  } else 
  if (window.ActiveXObject) {
    try {
      req = new ActiveXObject('Msxml2.XMLHTTP');
    } catch(e) {
      try {
        req = new ActiveXObject('Microsoft.XMLHTTP');
      } catch(e) {
        req = null;
      }
    }
  } else {
    req = null;
  }
  return req;
}

function drawGeozones(myJSONtext,recenter){
	try{
	var jsonText = eval("("+myJSONtext+")"); 
	}catch(e){
		alert(e);
	}	
	if(jsonText){
		//alert(jsonText);		
		var len = jsonText.length;		
		for(var i=0;i<len;i++){
			var gone = jsonText[i];
			var latMin = gone.latitudeMin;
			var latMax = gone.latitudeMax;
			var lonMin = gone.longitudeMin;
			var lonMax = gone.longitudeMax;
			
			var point1 = new VELatLong(latMin,lonMin);
			var point2 = new VELatLong(latMax,lonMin);
			var point3 = new VELatLong(latMax,lonMax);
			var point4 = new VELatLong(latMin,lonMax);
			
			var points = [];
			points.push(point1); 
			points.push(point2);
			points.push(point3);
			points.push(point4);
			
			var myShape = new VEShape(VEShapeType.Polygon, points);		
			virtEarthDrawLayer.AddShape(myShape);
		}		
		
	}else{
	}	
}

//FIXME ajax result parser
function handle(myJSONtext, recenter){

	try{
	var jsonText = eval("("+myJSONtext+")"); 
	}catch(e){
		alert(e);
	} 
				
	if(jsonText!=null){		
		var responseJson = document.getElementById('responseJson');
		// responseJson.innerHTML=myJSONtext;	
					
	 	var detailList = [];
    	var pointList = [];
    	var pushPinList = [];
    	var centerLat = 0.0;
    	var centerLon = 0.0;
    	var zoomFactor = -1;
    	var lastDev = '';
    	var rcdNdx = 0;
    	
    	
      	var maxLat = -90.0, maxLon = -180.0;
      	var minLat =  90.0, minLon =  180.0;
      	var startNdx = jsonText.length - MAX_PUSH_PINS - 1;
      	if (startNdx < 0) { startNdx = 0; }
      
      
	  for(i=0; i<jsonText.length; ++i){	  
	  		var evRcd = jsonText[i];
			var dev   = evRcd.device;
            var date  = evRcd.dateCreated;
            var time  = evRcd.timestamp;            
            var dtime = date;            
            var code  = evRcd.statusCode;
            var icon  = 1 ; //FIXME
            var lat   = evRcd.latitude;
            var lon   = evRcd.longitude;
            var kph   = evRcd.speed;
            var spd   = kph; //* 0.621371192237334;
            var hdg   = HEADING[Math.round((evRcd.heading+22.5)/45.0) % 8];
            var alt   = evRcd.altitude;
            var addr  = evRcd.address; 
            	           
            rcdNdx++;            
            if ((lat != 0) || (lon != 0)) {
              if (lat > maxLat) { maxLat = lat; }
              if (lat < minLat) { minLat = lat; }
              if (lon > maxLon) { maxLon = lon; }
              if (lon < minLon) { minLon = lon; }
              
              var point = new VELatLong(lat,lon)
              pointList.push(point);

              var x = new vearthCreatePushPin(dev,lat,lon,rcdNdx,code,icon,date,time,spd,hdg)                             
              pushPinList.push(x);
            }
            
            var vdp = new vearthDetailPoint(dev,lat,lon,rcdNdx,code,dtime,spd,hdg,alt,addr)
            detailList.push(vdp);
            
            //if (dtime > virtEarthLastEventTime) { virtEarthLastEventTime = dtime; }
            
            if (lastDev != null) {
              if (lastDev == '') {
                lastDev = dev;
              } else
              if (lastDev != dev) {
                lastDev = null;
              }
            }
		}//end for 
		
		centerLat = 0.0;
      	centerLon = 0.0;
      	//FIXME 
      	zoomFactor = -1;
      	
      	if (rcdNdx <= 0) {
      		detailList = [];
      	    pointList = [];
      	    pushPinList = [];
      		centerLat = 37.0;
      		centerLon = -118.0;
      		zoomFactor = 7.0;
    	}
    
    vearthSetMap(recenter,centerLat,centerLon,zoomFactor,pointList,pushPinList,(lastDev!=null));
    
    
    // var lastEventId = document.getElementById('lastEventTime');
    // if (lastEventId != null) { lastEventId.innerHTML = virtEarthLastEventTime; }
    virtEarthDetailPoints = detailList;
    vearthShowDetails();
    
    
    var geozoneurl = '/gts/device/getGeozonesAjax?id='+${device?.id}
    var req = vearthGetXMLHttpRequest();
    if (req) {
        req.open('GET', geozoneurl, true);
        req.onreadystatechange = function() {
              if (req.readyState == 4) {
                drawGeozones(req.responseText,recenter)
              } else  if (req.readyState == 1) {
              } else {
      		  }
    		}
    	req.send(null);
  	} else {
  	}
    
    
    return virtEarthDetailPoints.length;	
		
	}else{
		return 0;	
	}
}

//XXX  ajax call
function vearthLoadPoints(mapURL,recenter) {
  var req = vearthGetXMLHttpRequest();
  if (req) {
    req.open('GET', mapURL, true);
    req.onreadystatechange = function() {
      if (req.readyState == 4) {        
        handle(req.responseText,recenter)
      } else
      if (req.readyState == 1) {
      } else {
      }
    }
    req.send(null);
  } else {
  }
}
function vearthCreateCircle(pt,radiusMeters) {
  var radLat = geoRadians(pt.Latitude);
  var radLon = geoRadians(pt.Longitude);
  var d = radiusMeters / EARTH_RADIUS_METERS;
  var circlePoints = new Array();
  for (x = 0; x <= 360; x += 3) {
    var xrad   = geoRadians(x);
    var tmpLat = Math.asin(Math.sin(radLat) * Math.cos(d) + Math.cos(radLat) * Math.sin(d) * Math.cos(xrad));
    var tmpLon = radLon + Math.atan2(Math.sin(xrad) * Math.sin(d) * Math.cos(radLat), Math.cos(d)-Math.sin(radLat) * Math.sin(tmpLat));
    circlePoints.push(new VELatLong(geoDegrees(tmpLat),geoDegrees(tmpLon)));
  }
  var circleShape = new VEShape(VEShapeType.Polygon, circlePoints);
  circleShape.SetTitle('<small><b>' + pt.Latitude + ' / ' + pt.Longitude + '</b></small>');
  circleShape.HideIcon();
  circleShape.SetLineWidth(1);
  return circleShape;
}
function EventHandler_OnMouseUp(e) {
}
function EventHandler_OnMouseMove(e) {
  var latLon = virtEarthMap.PixelToLatLong(new VEPixel(e.mapX,e.mapY));
  var locDisp = document.getElementById('trackMapLatLonDisplay');
  if (locDisp != null) { locDisp.innerHTML = numFormatFloat(latLon.Latitude,4)+' / '+numFormatFloat(latLon.Longitude,4); }
  if (e.rightMouseButton == false) {
    document.getElementById('verth').style.cursor='crosshair';
    return false;
  } else {
    return true;
  }
}
function EventHandler_OnClick(e) {
  if (e.rightMouseButton) {
    var x = e.mapX, y = e.mapY;
    var latLon = virtEarthMap.PixelToLatLong(new VEPixel(x,y));
    virtEarthDrawLayer.DeleteAllShapes();
    virtEarthDrawLayer.AddShape(vearthCreateCircle(latLon,virtEarthZoneRadiusM));
    var zoneLat = document.getElementById('trackMapZoneLatitude');
    if (zoneLat != null) { zoneLat.value = latLon.Latitude; }
    var zoneLon = document.getElementById('trackMapZoneLongitude');
    if (zoneLon != null) { zoneLon.value = latLon.Longitude; }
  }
}
var recursiveRefresh = 0;


// XXX mapProviderUpdateMap
function mapProviderUpdateMap(mapURL,recenter) {

  if (recursiveRefresh != 0) { return; }
  recursiveRefresh++;
  try {
    vearthInit();
    vearthLoadPoints(mapURL,recenter);
  } catch(e) {
  }
  recursiveRefresh--;
}
function mapProviderToggleDetails() {
   virtEarthDetailsEnabled = !virtEarthDetailsEnabled;
   vearthShowDetails();
}
function mapProviderUnload() {
	// bla bla
	var a = 1+1;
}
//-->
</script>
<script type="text/javascript">
<!--
function trackMapOnLoad() {
  //calInit();
  trackMapUpdateMap(true);
}
function trackMapOnUnload() {
  mapProviderUnload();
}

var _uniqueURL = 0;

//onload 
function trackMapUpdateMap(recenter) {
  var dev = ${device.id};
  var url = '/gts/device/trackAjax?id='+dev;
  mapProviderUpdateMap(url,recenter);
    
}

//-->
</script>
<!-- End Page JavaScript -->

</head>

<body onload="javascript:trackMapOnLoad();" leftmargin='0'
	rightmargin='0' topmargin='0' bottommargin='0'>
<div id="spinner" class="spinner" style="display: none;"><img
	src="/gts/images/spinner.gif" alt="Spinner" /></div>
<div class="logo"><img src="/gts/images/grails_logo.jpg"
	alt="Grails" /></div>

<div class="nav"><span class="menuButton"><a class="home"
	href="${createLinkTo(dir:'')}">Home</a></span> <span class="menuButton"><g:link
	controller="device" class="list" acti n="list">Device List</g:link></span> <span
	class="menuButton"><g:link class="create" controller="device"
	action="create">New Device</g:link></span></div>

<div class="body" style="float: left;">
<h1>Show Device</h1>




<g:if test="${flash.message}">
	<div class="message">${flash.message}</div>
</g:if>

<div class="dialog">

<div class="devicecontent" style="float: left;">
<ul style="float: left; text-align: right;">
	<li>Id:</li>
	<li>Allow Notify:</li>

	<li>Devicegroup:</li>

	<li>Equipment Type:</li>

	<li>Imei Number:</li>

	<li>Is Active:</li>

	<li>Last Input State:</li>

	<li>Last Updated:</li>

	<li>Notes:</li>

	<li>Notify Action:</li>

	<li>Notify Email:</li>

	<li>Sim Phone Number:</li>
</ul>

<ul style="float: left; list-style-type: none;">
	<li><span id="deviceid">${device.id}</span></li>

	<li>${device.allowNotify}</li>

	<li><g:link controller="track" action="trackgroup"
		id="${device?.devicegroup?.id}">${device?.devicegroup} Map</g:link></li>
	<li>${device.equipmentType}</li>

	<li>${device.imeiNumber}</li>


	<li>${device.isActive}</li>

	<li>${device.lastInputState}</li>

	<li>${device.lastUpdated}</li>

	<li>${device.notes}</li>

	<li>${device.notifyAction}</li>

	<li>${device.notifyEmail}</li>

	<li>${device.simPhoneNumber}</li>
</ul>

</div>

<div id='verth' style='position: relative; width: 680px; height: 420px;'></div>
<div><b>Location Details</b>&nbsp;&nbsp(<a
	href='javascript:mapProviderToggleDetails()'>toggle show</a>) <span
	id='trackMapDataTable' style='margin-left: 15px;'></span></div>
<div id="responseJson"></div>

</div>
</div>



</body>